const { validationResult, buildCheckFunction } = require("express-validator")
const { isValidObjectId }  = require('mongoose')

exports = module.exports = validations => {
  return async (req, res, next) => {
    await Promise.all(validations.map(validation => validation.run(req)))

    const errors = validationResult(req)
    if (errors.isEmpty()) {
      return next()
    }

    res.status(200).json({
      code: 500,
      msg: errors.array()
    })
  }
}

exports.isValidObjectId = (location, fields) => {
  return buildCheckFunction(location)(fields).custom(async value => {
    if (!isValidObjectId(value)) {
      return Promise.reject('ID 格式错误')
    }
  })
}